



#include "Time.h"


#ifdef WIN32
#include <Windows.h>

static LARGE_INTEGER s_Frequency;

Time::Time()
:m_Data(new LARGE_INTEGER)
{
	QueryPerformanceFrequency(&s_Frequency);
	QueryPerformanceCounter((LARGE_INTEGER*)m_Data);
}
Time::~Time()
{
	delete m_Data;
}

void Time::update()
{
	QueryPerformanceCounter((LARGE_INTEGER*)m_Data);
}

long Time::diff_usec(const Time& time)const
{
	double diff = (double)(((LARGE_INTEGER*)m_Data)->QuadPart - ((LARGE_INTEGER*)time.m_Data)->QuadPart);
	return round(diff / s_Frequency.QuadPart * 1e6);
}
long Time::diff_msec(const Time& time)const
{
	double diff = (double)(((LARGE_INTEGER*)m_Data)->QuadPart - ((LARGE_INTEGER*)time.m_Data)->QuadPart);
	return round(diff / s_Frequency.QuadPart * 1e3);
}
long Time::diff_sec(const Time& time)const
{
	double diff = (double)(((LARGE_INTEGER*)m_Data)->QuadPart - ((LARGE_INTEGER*)time.m_Data)->QuadPart);
	return round(diff / s_Frequency.QuadPart);
}
#endif


#ifdef __linux__

#include <sys/time.h>
#include <unistd.h>
Time::Time()
    :m_Data(new timeval())
{
    
}
Time::~Time()
{
    delete (timeval*)m_Data;
}

void Time::update()
{
    gettimeofday((timeval*)m_Data,NULL);
}
long Time::diff_usec(const Time& time)const
{
    const timeval* left = (const timeval*)m_Data;
    const timeval* right = (const timeval*)time.m_Data;
    return round( (left->tv_sec - right->tv_sec)*1e6 + left->tv_usec - right->tv_usec);
}


long Time::diff_msec(const Time& time)const
{
    const timeval* left = (const timeval*)m_Data;
    const timeval* right = (const timeval*)time.m_Data;
    return round( (left->tv_sec - right->tv_sec)*1e3 + round( (left->tv_usec - right->tv_usec)/1e3) );
}
    
long Time::diff_sec(const Time& time)const
{
    const timeval* left = (const timeval*)m_Data;
    const timeval* right = (const timeval*)time.m_Data;
    return (left->tv_sec - right->tv_sec) + round( (left->tv_usec - right->tv_usec)/1e6 );
}

#endif


long Time::round(double num)
{
	if (num < 0) return (long)(num-0.5);
	else return (long)(num+0.5);
}
